const gulp = require('gulp'),
    babel    = require("gulp-babel"),
    uglify = require('gulp-uglify'),
    buffer = require('vinyl-buffer'),
    sourcemaps = require('gulp-sourcemaps'),
    source = require('vinyl-source-stream'),
    gutil = require('gulp-util'),
    browserify = require('browserify'),
    babelify = require('babelify'),
    sass = require('gulp-sass');

gulp.task('copyHtml', function () {
    return gulp.src('*.html')
        .pipe(gulp.dest('dist'));
});

gulp.task('scripts', function () {
    return browserify({
        basedir: '.',
        debug: true,
        entries: ['./main.js'],
        cache: {},
        packageCache: {}
    })
        .transform(babelify, {  //此处babel的各配置项格式与.babelrc文件相同
            presets: ['es2015']
        })
        .bundle()
        /*防止编译报错gulp退出执行*/
        .on('error', function(err) {
            gutil.log('错误信息：', err.message);
            return;
        })
        .pipe(source('bundle.js'))
        .pipe(buffer())
        .pipe(sourcemaps.init({loadMaps: true}))
        .pipe(sourcemaps.write('./'))
        .pipe(gulp.dest('dist'));
});

gulp.task('sass', function(){
    //sass()方法用于转换sass到css
    return gulp.src('./css/style.scss')
        .pipe(sass()) // Converts Sass to CSS with gulp-sass
        .pipe(gulp.dest('dist'))
});

gulp.task('watch', function () {
    gulp.watch(['src/*.js','component/*.js'], ['scripts']);
    gulp.watch('./*.html', ['copyHtml']);
    gulp.watch('*.scss', ['sass']);
});

gulp.task('start', ['scripts', 'watch','copyHtml','sass']);